/**
 * 
 */
package com.flycms.web.front.rest;

import java.util.Date;
import java.util.Map;
import java.util.Objects;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.flycms.core.base.BaseController;
import com.flycms.core.entity.RestDataVo;
import com.flycms.core.utils.web.utils.CommonUtils;
import com.flycms.module.comment.model.FlyContentType;
import com.flycms.module.comment.model.OptionCount;
import com.flycms.module.comment.model.Votes;
import com.flycms.module.comment.service.CollectsService;
import com.flycms.module.comment.service.VotesService;
import com.flycms.module.message.service.MessageService;
import com.flycms.module.user.model.User;

/**
 *
 * <br/>Copyright 2020
 * <br/>All rights reserved
 * @author 沁言訫語
 * @version 2020年2月20日
 * @Date 2020年2月20日
 */

@RestController
@RequestMapping("/vt")
public class VoteController extends BaseController {

    private static final Logger logger = LogManager.getLogger(VoteController.class);
    
    @Autowired
    protected VotesService votesService;
    
    @Autowired
    protected CollectsService collectsService;
    
    @Autowired
    protected MessageService messageService;
    
    /**
     * 进行点赞
     * @param contentType
     * @param contentId
     * @param map
     * @return
     * @author 沁言訫語
     */
    
    @PostMapping(value = {"/u/vote/{contentType}/{contentId}"})
    public RestDataVo addVote(@PathVariable("contentType") String contentType,
            @PathVariable("contentId") Long contentId,
            @RequestBody Map<String, Object> map) {
        RestDataVo rest = null;
        Long userId = getUserId();
        Votes vote = new Votes();
        FlyContentType ct = null;
        if (map != null && map.containsKey("voteType")
                && map.get("voteType") != null) {
            String voteType = CommonUtils.transToString(map.get("voteType"));
            Integer vt = CommonUtils.validVoteType(voteType);
            ct = CommonUtils.getContentType(contentType);
            if (vt == null || ct == null) {
                return RestDataVo.ERROR("点赞失败，请检查传入参数，{0}:{1}", contentType, contentId + "");
            }
            vote.setVoteType(vt);
        } else {
            return RestDataVo.ERROR("缺少必要参数");
        }
        User toUser = null;
        try {
            Object obj = collectsService.queryContentObject(contentId, ct);
            if (obj == null) {
                return RestDataVo.ERROR("评论的内容不存在");
            }
            toUser = CommonUtils.getOwner(obj);
        } catch (Exception e) {
            logger.error("", e);
            return RestDataVo.ERROR("评论异常");
        }
        try {
            Votes v = votesService.queryVotedVote(userId, contentId, ct);
            if (v != null) {
                //点过了
                if (Objects.equals(v.getVoteType(), vote.getVoteType())) {
                    rest = RestDataVo.ERROR("重复点赞/点踩");
                } else {
                    //改变赞/踩
                    v.setVoteType(vote.getVoteType());
                    v.setUpdateTime(new Date());
                    OptionCount o = votesService.updateVote(v, ct);
//                    OptionCount o = votesService.recordVoteCount(vote, ct);
                    messageService.addSystemMessage(userId, toUser.getUserId(), ct.msg(),
                            CommonUtils.getCommentMessageModel(toUser.getUserName(), ct.msg(), ""));
                    rest = RestDataVo.OK(o);
                }
            } else {
                vote.setCreateTime(new Date());
                vote.setUserId(userId);
                vote.setContentId(contentId);
                //新增点赞数据
                OptionCount o = votesService.addVote(vote, ct);
//                OptionCount o = votesService.recordVoteCount(vote, ct);
                messageService.addSystemMessage(userId, toUser.getUserId(), ct.msg(),
                        CommonUtils.getCommentMessageModel(toUser.getUserName(), ct.msg(), ""));
                rest = RestDataVo.OK(o);
            }
        } catch (Exception e) {
            logger.error("", e);
            rest = RestDataVo.ERROR("操作失败");
        }
        return rest;
    }
    
    
}
